﻿using Games.Basic;
using Games.Common;
using Games.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using Xamarin.Forms;

namespace Games
{
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        private SettingsModel model;
        private IMediaHandler media;
        private List<string> orders = new List<string> {
            "马踏棋盘","独立钻石",
            "八宝盒","华容道",
            "八数码","推箱子",
            "九宝莲灯","数同",
            "眼疾手快","聚精会神",
            "连环灯","方块消消"
        };
        public MainPage()
        {
            InitializeComponent();
            this.media = DependencyService.Get<IMediaHandler>();
        }

        public MainPage(SettingsModel settings) : this()
        {
            BindingContext = model = settings;
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();
            DependencyService.Get<IRotateHandler>().ForcePortrait();
            if(gridmenu.Children.Count > 0)
            {
                return;
            }
            //NavigationPage.SetHasNavigationBar(this, false);
            var items = DependencyService.Get<GamePageManager>().GetAllGames().OrderBy(x => x.BuildDate).ToList();
            var list = new List<IGameInfo>();
            foreach(var item in orders)
            {
                var i = items.FirstOrDefault(x => x.Name == item);
                if(i != null)
                {
                    list.Add(i);
                    items.Remove(i);
                }
            }
            list.AddRange(items);

            var rows = (list.Count + 1) / 2;
            for(int i = 0; i < rows; i++)
            {
                gridmenu.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
            }
            gridmenu.RowDefinitions.Add(new RowDefinition { Height = GridLength.Star });

            var layopt = new LayoutOptions(LayoutAlignment.Fill, true);
            var index = 0;
            foreach(var item in list)
            {
                var btn = new Button { Text = item.Name, HorizontalOptions = layopt, Margin = new Thickness(5, 5) };
                btn.BindingContext = item;
                btn.Clicked += (s, e) => Open(item);
                gridmenu.Children.Add(btn, index % 2, index / 2);
                index++;
            }
            //this.ShowToastMessage("开始玩游戏喽~~");
        }

        private void Open(IGameInfo game)
        {
            var page = game.NewPage();
            if(page != null)
            {
                if(page.Parent == null)
                {
                    Navigation.PushAsync(page);
                }
            }
            else
            {
                DisplayAlert(game.Name, "项目不存在", "OK");
            }
        }

        private DateTime lastTime = DateTime.MinValue;
        private int clickCount = 0;
        private void Footer_Tapped(object sender, EventArgs e)
        {
            if(Utils.NoMaxLimit)
                return;
            var now = DateTime.Now;
            if(now.Subtract(lastTime).Milliseconds < 500)
            {
                if(++clickCount >= 7)
                {
                    Utils.NoMaxLimit = true;
                    (sender as Label).TextColor = Color.Gold;
                }
            }
            else
            {
                clickCount = 1;
            }
            lastTime = now;
        }

        private DateTime? lastBackKeyDownTime;
        protected override bool OnBackButtonPressed()
        {
            if(!lastBackKeyDownTime.HasValue || DateTime.Now - lastBackKeyDownTime.Value > new TimeSpan(0, 0, 2))
            {
                lastBackKeyDownTime = DateTime.Now;
                this.ShowToastMessage("再按一次退出");
                return true;
            }
            return base.OnBackButtonPressed();
        }

        private async void Music_Tap(object sender, EventArgs e)
        {
            var database = DependencyService.Get<IDataBase>();
            if(App.Settings.MusicIsOn)
            {
                this.media.Stop();
            }
            else
            {
                this.media.Play();
            }
            App.Settings.MusicIsOn = !App.Settings.MusicIsOn;
            model.Music = App.Settings.MusicIsOn ? "开" : "关";
            await database.SaveAsync(App.Settings);
        }
    }
}
